package com.hm.admin.web;


import com.hm.admin.domain.HmAdmin;
import com.hm.admin.service.HmAdminPermissionService;
import com.hm.admin.service.HmAdminRoleService;
import com.hm.admin.service.HmAdminService;
import com.hm.admin.util.JacksonUtil;
import com.hm.admin.util.ResponseUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.hm.admin.util.constant.AdminResponseCode.ADMIN_INVALID_ACCOUNT;

@RestController
@RequestMapping("/hmadmin/auth")
public class AdminAuthController {
    private final Logger logger = LoggerFactory.getLogger(AdminAuthController.class);


    @Autowired
    private HmAdminService adminService;

    @Autowired
    private HmAdminRoleService roleService;

    @Autowired
    private HmAdminPermissionService permissionService;

    /*
     *  { username : value, password : value }
     */
    @PostMapping("/login")
    public Object login(@RequestBody String body) {
        String username = JacksonUtil.parseString (body, "username");
        String password = JacksonUtil.parseString(body, "password");

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResponseUtil.badArgument();
        }

        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(new UsernamePasswordToken(username, password));
        } catch (UnknownAccountException uae) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号或密码不正确");
        } catch (LockedAccountException lae) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, "用户帐号已锁定不可用");

        } catch (AuthenticationException ae) {
            return ResponseUtil.fail(ADMIN_INVALID_ACCOUNT, ae.getMessage());
        }
        currentUser.getSession().getId();
        return ResponseUtil.ok(currentUser.getSession().getId());
    }

    @RequestMapping("/test")
    public Map test() {
        List<HmAdmin> admins=adminService.findAdmin("admin123");
        for(HmAdmin admin:admins){
            logger.info(admin.getUsername());
        }
        Map result=new HashMap();
        result.put("code",0);
        result.put("data",123456);
        result.put("msg","成功");
        return result;
    }

    /*
     *
      */
    @RequiresAuthentication
    @PostMapping("/logout")
    public Object login() {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return ResponseUtil.ok();
    }


    @RequiresAuthentication
    @GetMapping("/info")
    public Object info() {
        Subject currentUser = SecurityUtils.getSubject();
        HmAdmin admin = (HmAdmin) currentUser.getPrincipal();

        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());

        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.queryByIds(roleIds);
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);
        data.put("roles", roles);
        data.put("perms", permissions);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/401")
    public Object page401() {
        return ResponseUtil.unlogin();
    }

    @GetMapping("/index")
    public Object pageIndex() {
        return ResponseUtil.ok();
    }

    @GetMapping("/403")
    public Object page403() {
        return ResponseUtil.unauthz();
    }


}
